﻿using AutoMapper;
using Hx.DataTransferObject;
using Hx.Domain.Model;
using Hx.Domain.Repositories;
using Hx.Infrastructure.Common;
using Hx.Infrastructure.Helpers;
using Hx.Infrastructure.Services;

namespace Hx.Application.Implementation
{
    public class AuthorImplementation
    {
        private readonly IAuthorRepository _authorRepository;

        public AuthorImplementation()
        {
            _authorRepository = ServiceLocator.Instance.GetService<IAuthorRepository>();
        }

        public CommonResult<AuthorObject> CheckLogin(string userName, string password)
        {
            var author = _authorRepository.GetAuthorByUserName(userName);
            if (author == null)
            {
                return new CommonResult<AuthorObject>
                {
                    Result = false,
                    Message = "用户不存在!"
                };
            }

            var pwd = EncryptPassword(password, author.PasswordSalt);
            if (pwd == author.Password)
            {
                return new CommonResult<AuthorObject>
                {
                    Result = true,
                    Message = "OK",
                    ResultEntity = Mapper.Map<Author, AuthorObject>(author)
                };
            }

            return new CommonResult<AuthorObject>
            {
                Result = false,
                Message = "密码错误"
            };
        }

        /// <summary>
        ///     根据盐度产生加密密码
        /// </summary>
        /// <param name="password">密码</param>
        /// <param name="salt">盐度</param>
        private static string EncryptPassword(string password, string salt)
        {
            var pwd = SecurityHelper.Sha1Encrypt(password);
            pwd += salt;
            return SecurityHelper.Sha1Encrypt(pwd);
        }
    }
}
